import React, { useState, useEffect } from 'react';
import { Button, Table, Input, Space, Select, Modal, Form, message, DatePicker } from 'antd';
import { editProduce, getMaterial } from '@/api/services';
import { v4 as uuidv4 } from 'uuid'; // 导入 uuid 库
import moment from 'moment';


interface childrenProps {
    onCancel: () => void;
    editId: any,
    getProduceList: () => void;
}

interface ProductDetail {
    key: string; // 新增一个 key 属性作为唯一标识符
    product: string;
    quantity: number;
}

const InfoModal: React.FC<childrenProps> = ({ onCancel, editId, getProduceList }) => {
    const [form] = Form.useForm();
    const [materialDetails, setMaterialDetails] = useState<any>([]);
    const user = JSON.parse(localStorage.getItem('user') as any);
    const [material, setMaterial] = useState<any>([]);//原材料列表

    useEffect(() => {
        // 初始化时添加两个空的产品明细行
        setMaterialDetails([{ key: uuidv4(), product: '', quantity: 0 }]);
    }, []);

    //获取仓库原料
    useEffect(() => {
        getMaterial().then((res: any) => {
            console.log(res);
            const options = res.results.map((goods: any) => ({
                value: goods.goods_name,
                label: goods.goods_name,
            }));
            setMaterial(options);
        })
    }, [])

    
    const saveProduce = async () => {
        const validate = await form.validateFields();
        const materialDetail = Object.values(materialDetails).map((item: any) => `${item.product}||${item.quantity}`).join('||');
        const currentTime = moment().format('YYYY-MM-DD HH:mm:ss');
        editProduce({
            productId: editId,
            mtdetail: materialDetail,
            posttime: currentTime,
            deadline: moment(validate.product_deadline).format('YYYY-MM-DD HH:mm:ss'),
        }).then((res: any) => {
            console.log(res);
            message.success('编辑成功');
            getProduceList();
            onCancel();
        })
    }

    const handleAddProduct = () => {
        const newProductDetail: ProductDetail = {
            key: uuidv4(), // 使用 uuid 生成唯一标识符
            product: '',
            quantity: 0,
        };
        setMaterialDetails([...materialDetails, newProductDetail]);
    };

    const handleProductChange = (key: number, value: string) => {
        const updatedProductDetails = materialDetails.map((detail: { key: number; }) => {
            if (detail.key === key) {
                return { ...detail, product: value };
            }
            return detail;
        });
        setMaterialDetails(updatedProductDetails);
        console.log(updatedProductDetails)

    };

    const handleQuantityChange = (key: number, value: any) => {
        const updatedProductDetails = materialDetails.map((detail: { key: number; }) => {
            if (detail.key === key) {
                return { ...detail, quantity: value };
            }
            return detail;
        });
        setMaterialDetails(updatedProductDetails);

    };

    const detailColumns: any = [
        {
            title: '原料',
            dataIndex: 'material',
            render: (_: any, record: any) => (
                <Select
                    style={{ width: 120 }}
                    onChange={(value) => handleProductChange(record.key, value)}
                    options={material}
                />
            )
        },
        {
            title: '数量',
            dataIndex: 'quantity',
            render: (_: any, record: any) => (
                <Input value={record.nums} onChange={(e) => handleQuantityChange(record.key, e.target.value)} />
            )
        }
    ]
    //新增订单footer
    const ModalFooter = (
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button
                type="primary"
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={saveProduce}
            >
                确定
            </Button>
            <Button
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={onCancel}
            >
                取消
            </Button>
        </div>
    )
    return (
        <Modal
            open={true}
            title="编辑生产订单"
            onCancel={onCancel}
            footer={ModalFooter}
        >
            <Form
                form={form}
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 14 }}
            >
                {/* <Form.Item label="产物明细" name="customerCompany">
                    
                </Form.Item> */}
                <Form.Item label="原料明细" name="product_mtdetail">
                    <Table
                        columns={detailColumns}
                        dataSource={materialDetails}
                        pagination={false}
                        bordered
                    />
                    <Button type="dashed" onClick={handleAddProduct} style={{ marginTop: '20px' }}>
                        增加原料
                    </Button>
                </Form.Item>
                <Form.Item label="生产截止时间" name="product_deadline">
                    <DatePicker
                        showTime
                        onChange={(value, dateString) => {
                            console.log('Selected Time: ', value);
                            console.log('Formatted Selected Time: ', dateString);
                        }}
                    />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default InfoModal;
